package com.project.api.ym.dao;

import com.project.api.ym.model.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class OrderDao {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;

    public Order GetOrderById(long id){
        Order res=new Order();
        String sql = "SELECT * FROM "+ Order.tableName +" where `id`=?";
        try {
            res = (Order) mainJdbcTemplate.queryForObject(
                    sql, new Object[] {id},new BeanPropertyRowMapper(Order.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return res;
        }
        return res;
    }

    public int GetOrderCount(String condition){
        String sql = "select count(*) from "+Order.tableName;
        if (condition!=null && !condition.equalsIgnoreCase("")){
            sql=sql+" where 1=1 "+condition;
        }
        int count = mainJdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    public List<Order> GetOrder(String condition){
        List<Order> res = new ArrayList<>();
        String sql = "SELECT * FROM "+ Order.tableName ;
        if (condition!=null && !condition.equalsIgnoreCase("")){
            sql=sql+" where 1=1 "+condition;
        }
        try {
            res = mainJdbcTemplate.query(
                    sql, new Object[] {},new BeanPropertyRowMapper(Order.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return res;
        }
        return res;
    }

    public int RefundOrder(String order_num,String refund_num,String refund_price,long rtime){
        String sql = "update "+ Order.tableName + "set is_refund=1 , refund_num=? , refund_price=? , rtime=? ";
        sql= sql + " where order_num=? ";
        return mainJdbcTemplate.update(sql, refund_num,refund_price,rtime,order_num);
    }
}
